/*
 * $Id: MixedStreamCopier.java,v 1.2 2009/07/24 18:34:01 oliver Exp $
 *
 * Copyright (C) 2006 General Electric Company. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 *
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

package org.simplx.xstream;

import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.simplx.xstream.MixedStreamReader.TextPart;

import java.util.Iterator;

/**
 * A class that copies mixed streams.
 *
 * @author Ken Arnold
 */
public class MixedStreamCopier {
    /** Creates a new {@link MixedStreamCopier}. */
    public MixedStreamCopier() {
    }

    /**
     * Copies a mixed stream to a destination writer.
     *
     * @param source      The mixed stream source.
     * @param destination The copy destination.
     */
    public void copy(MixedStreamReader source,
            HierarchicalStreamWriter destination) {

        doCopy(source, destination, false);
    }

    private void doCopy(MixedStreamReader source,
            HierarchicalStreamWriter destination, boolean startNode) {

        if (startNode)
            destination.startNode(source.getNodeName());
        int attributeCount = source.getAttributeCount();
        for (int i = 0; i < attributeCount; i++) {
            destination.addAttribute(source.getAttributeName(i),
                    source.getAttribute(i));
        }
        Iterator parts = source.partIterator();
        while (parts.hasNext()) {
            Object part = parts.next();
            if (part instanceof TextPart)
                destination.setValue(((TextPart) part).contents());
            else {
                source.moveDown();
                doCopy(source, destination, true);
                source.moveUp();
            }
        }
        if (startNode)
            destination.endNode();
    }
}
